package com.zy.dsms.controller;

import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.zy.dsms.pojo.User;

/** 
* @author  wj  
* @version 创建时间：2018年8月22日 上午10:00 
* 类说明  用户类
*/
@Controller
public class UserController {
	
	/**
	 * 去登录页面
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request){
		String basePath = request.getContextPath();
		request.getSession().setAttribute("basePath", basePath);
		return "index";
	}
	/**
	 * 执行登录操作
	 */
	@RequestMapping("/doLogin")
	@ResponseBody
	public ModelAndView doLogin(User record){
		ModelAndView model = new ModelAndView();
		UsernamePasswordToken token = new UsernamePasswordToken(record.getUserId(),record.getUserPassword());
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		int status=500;
		String message = "登录失败！";
		String back_url= "";
		try{
			subject.login(token);
			User user = (User)subject.getPrincipal();
			session.setAttribute("user", user);
			status = 200;
			message = "登陆成功！";
			back_url = "Home";
		}catch(Exception e){
			back_url = "index";
			e.printStackTrace();
		}
		model.addObject("message", message);
		model.addObject("status", status);
		model.setViewName(back_url);
		return model;
	}

}
